import os
import re
import time
import requests
import json
import sys

def login_start():
    headers = {
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'LogStatistic',
        'Sec-Fetch-User': '?1',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Fetch-Mode': 'navigate',
        'Referer': 'https://cas.dgut.edu.cn/home/Oauth/getToken/appid/illnessProtectionHome/state/home.html',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8',
    }
    url = 'https://cas.dgut.edu.cn/home/Oauth/getToken/appid/illnessProtectionHome/state/home.html'
    reposed = requests.get(url=url, headers=headers)
    reposed_token = str(reposed.content)
    reposed_cookies = reposed.cookies.get_dict()
    # print(reposed_cookies)
    token = re.findall(r'var token = "(.+?)";', reposed_token)
    print('token = ' + token[0])
    return token[0], reposed_cookies


def login(token, cookies, user, password):
    token1 = token
    url = 'https://cas.dgut.edu.cn/home/Oauth/getToken/appid/illnessProtectionHome/state/home'
    headers = {
        'Host': 'cas.dgut.edu.cn',
        'Connection': 'keep-alive',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Origin': 'https://cas.dgut.edu.cn',
        'X-Requested-With': 'XMLHttpRequest',
        'User-Agent': 'LogStatistic',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-Mode': 'cors',
        'Referer': 'https://cas.dgut.edu.cn/home/Oauth/getToken/appid/illnessProtectionHome/state/home.html',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8',

    }
    data = {
        'username': user,
        'password': password,
        '__token__': token1,
        'wechat_verify': '',
    }


    reposed = str(requests.post(url=url, headers=headers, data=data, cookies=cookies).content)
    token2 = re.findall(r'token=(.+?)&', reposed)
    msg = re.findall(r'message.....(.+?).....code', reposed)
    if msg[0] == '\\"\\xe9\\xaa\\x8c\\xe8\\xaf\\x81\\xe9\\x80\\x9a\\xe8\\xbf\\x87\\\\':
        msg = '验证通过'
    else:
        msg = 'msg错误'
    # print(reposed)
    # print(token2)
    print('token2 = ' + token2[0])
    print('msg = ' + msg)
    return token2[0], msg


def login_end(token2, cookies):
    url = f'https://yqfk.dgut.edu.cn/auth/auth/login?token={token2}&state=home'
    # print(url)
    headers = {
        'Host': 'yqfk.dgut.edu.cn',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'LogStatistic',
        'Sec-Fetch-User': '?1',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Fetch-Mode': 'navigate',
        'Referer': 'https://cas.dgut.edu.cn/home/Oauth/getToken/appid/illnessProtectionHome/state/home.html',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8',
    }

    params = {
        'token': token2,
        'state': 'home',
    }
    access_url = str(requests.get(url=url, headers=headers, params=params, cookies=cookies).url)  # 可以直接返回重定向的url
    access_token = re.findall(r'access_token=(.+)', access_url)
    print('accesstoken = ' + access_token[0])
    return access_token[0]


def qiandao(access_token):
    url = 'https://yqfk.dgut.edu.cn/home/base_info/addBaseInfo'
    headers = {
        'Connection': 'keep-alive',
        'Accept': 'application/json',
        'Origin': 'https://yqfk.dgut.edu.cn',
        'authorization': f'Bearer {access_token}',
        'User-Agent': 'LogStatistic',
        'Content-Type': 'application/json; charset=utf-8',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-Mode': 'cors',
        'Referer': 'https://yqfk.dgut.edu.cn/main',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8',
    }
    datatimenow = time.strftime("%Y-%m-%d", time.localtime())
    # (type(datatimenow))
    # print(datatimenow)
    #data_json = json.dumps(data)
    #reposed = requests.post(url=url, headers=headers, data=data_json).json()
    # code = re.findall(r'code":(.+?),"info', reposed)
    with open("./a.json", 'r', encoding='utf-8') as data_json:
        data_dic = json.load(data_json)
    data_dic['submit_time'] = datatimenow
    data_json = json.dumps(data_dic)
    reposed = requests.post(url=url, headers=headers, data=data_json).json()
    print(reposed['message'])
    return reposed['message']

## 通知
class WXPusher:
    def __init__(self, usr, msg):
        self.base_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?'
        self.req_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='
        self.corpid = ''     # 填写你的企业id
        self.corpsecret = ''     # 填写你应用的secret
        self.agentid =          # 填写你的应用id，不加引号，是个整型常数
        self.usr = usr
        self.msg = msg

    def get_access_token(self):
        urls = self.base_url + 'corpid=' + self.corpid + '&corpsecret=' + self.corpsecret
        resp = requests.get(urls).json()
        access_token = resp['access_token']
        return access_token

    def send_message(self):
        data = self.get_message()
        req_urls = self.req_url + self.get_access_token()
        res = requests.post(url=req_urls, data=data)
        print(res.text)

    def get_message(self):
        data = {
            "touser": self.usr,
            "toparty": "@all",
            "totag": "@all",
            "msgtype": "textcard",
            "agentid": self.agentid,
            "textcard": {
                "title":"疫情打卡签到",
                "description": self.msg,
                "url":"https://yqfk.dgut.edu.cn/main",
                "btntxt":"更多"
            },
            "safe": 0,
            "enable_id_trans": 0,
            "enable_duplicate_check": 0,
            "duplicate_check_interval": 1800
        }
        data = json.dumps(data)
        return data

def start(user,password,usr):
    user = user
    password = password
    token, cookies = login_start()
    token2, msg = login(token, cookies, user, password)
    access_token = login_end(token2, cookies)
    message = qiandao(access_token)
    datatimenow = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    if message == '提交成功':
        msg = f'{user},打卡成功\n{datatimenow}'
    elif message == '今日已提交，请勿重复操作':
        msg = f'{user},今日已提交，请勿重复操作\n{datatimenow}'
    else:
        msg = f'{user},打卡失败，请检查原因！！\n{datatimenow}'
    test = WXPusher(usr=usr, msg=msg)  
    test.send_message()


if __name__ == '__main__':
    user = '' # 填写你账号
    password = '' # 填写你的密码
    usr='' #填写你的推送用户名 usr参数为推送用户名
    start(user, password,usr)

